﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework;
using System.Threading;
using Microsoft.Xna.Framework.Graphics;

namespace Jemgine.Engine
{
	partial class Simulation
	{
		public void EndSimulation()
		{
			for (int i = 0; i < Entities.Count; ++i)
				if (Entities[i].state != Jemgine.Data.EntityRecord.State.PreCreated) Entities[i].Destroy();
            Entities.Clear();
            
            _created = new BufferedList<Data.ScriptNode>();
            _destroyed = new BufferedList<Data.EntityRecord>();
            _createdJoints = new BufferedList<Jemgine.Data.Dynamic>();

			foreach (Module _module in Modules)
				_module.EndSimulation();
		}

        public void BeginSimulation()
        {
            TickCount = 0;
            SupressPhysics = false;
            foreach (Module _module in Modules) _module.BeginSimulation();
        }

		private String GetAssetName(String FileName)
		{
			return FileName.Substring(0, FileName.IndexOf('.'));
		}

        public void DefaultElementHandler(Data.MapElement A)
        {
            if (A is Data.ScriptNode)
            {
                if (A is Data.EntityRecord)
                    (A as Data.EntityRecord).state = Jemgine.Data.EntityRecord.State.Limbo;
                _created.Add(A as Data.ScriptNode);
            }
            if (A is Data.Dynamic) _createdJoints.Add(A as Data.Dynamic);
        }

        public void ImportMap(Data.MapData Import, Vector2 Offset, Action<Data.MapElement> ElementHandler)
        {
            Import.PostProcess(this, Offset, ElementHandler);
        }

        public bool ImportMap(out Data.MapData Import,
            String MapName,
            Vector2 Offset,
            bool IsBaseMap,
            Action<Data.MapElement> ElementHandler)
        {
            Import = null;

            try
            {
                Import = new Data.MapData(EpisodeContent.Load<Jemgine.Data.MapData>(MapName));
            }
            catch (ContentLoadException)
            {
                return false;
            }

            ImportMap(Import, Offset, ElementHandler);

            if (IsBaseMap)
            {
                RawMap = Import;
                MapHeader = Import.Header;
                MapHeader.Gravity.Normalize();
            }

            return true;
        }
	}
}
